<template>
    <!-- 对话框表单 -->
    <el-dialog title="编辑" v-model="visible" :close-on-click-modal="false" :destroy-on-close="true" @close="closeFun">
        <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="锚文本名" prop="name">
                <el-input v-model="formData.name" placeholder="请输入锚文本名" maxlength="500" clearable />
            </el-form-item>
            <el-form-item label="pc端链接" prop="p_url">
                <el-input v-model="formData.p_url" placeholder="请输入pc端链接" maxlength="500" clearable />
            </el-form-item>
            <el-form-item label="m端链接" prop="m_url">
                <el-input v-model="formData.m_url" placeholder="请输入m端链接" maxlength="500" clearable />
            </el-form-item>
            <el-row>
                <el-col style="text-align: center;" :span="24">
                    <el-button @click="closeFun()">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                </el-col>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, defineExpose, inject, defineEmits } from 'vue';
import { addAnchor, editAnchor } from '@/api/anchor';

let emit = defineEmits(['update']);
let used = inject('used');//公共方法
let visible = ref(false);//是否显示
let formData = reactive({
    name: '',
    p_url: '',
    m_url: '',
});//表单数据
let ruleFormRef = ref(null);//表单
//表单验证
const rules = reactive(
    {
        name: [
            { required: true, message: '请输入锚文本名', trigger: 'blur' },
        ],
        p_url: [
            { required: true, message: '请输入pc端链接', trigger: 'blur' },
        ],
        m_url: [
            { required: true, message: '请输入m端链接', trigger: 'blur' },
        ],
    }
)
//显示
const show = (row) => {
    if (row) {
        Object.assign(formData, row);

    } else {
        Object.assign(formData, {
            name: '',
            p_url: '',
            m_url: '',
        });
    }
    visible.value = true;
};
//关闭
const closeFun = () => {
    visible.value = false;
};

//提交
const submitForm = async (formEl) => {
    let params = used.deepClone(formData)
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            console.log(params)
            let res = await (params.id ? editAnchor(params, 'post') : addAnchor(params, 'post'));
            if (res.code == 1) {
                used.msgSuccess('更新成功')
                closeFun();
                emit('update')
            } else {
                used.msgError(res.message)
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
//
defineExpose({
    show
})
</script>

<style scoped lang="scss"></style>
